# -*- coding: utf-8 -*-
# @Author: gengxd
# @Time:   2020-6-22 17:52
# @File:   script


# 导入配置文件
from lib.conf.config import settings

# 导入相关库文件
import smtplib
import os

# 构建邮件文本
from email.mime.text import MIMEText
# 负责将多个对象集合起来
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.image import MIMEImage


def sendmail():
    #  构建邮件内容、附件
    if not settings.MAILBODY and os.getenv(MAILBODY):
        settings.MAILBODY = os.getenv(MAILBODY)
    if settings.MAILTYPE == 'text':
        msg = MIMEText(settings.MAILBODY, settings.MAILCONTENTFMT, settings.MAILCONTENTCODE)
    elif settings.MAILTYPE == 'HTML':  # 发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html
        msg = MIMEText(settings.MAILBODY, settings.MAILCONTENTFMT, settings.MAILCONTENTCODE)
    elif settings.MAILTYPE == 'ATTA':
        # 邮件正文
        msg = MIMEMultipart()
        msg.attach(MIMEText(settings.MAILBODY, settings.MAILCONTENTFMT, settings.MAILCONTENTCODE))

        # 邮件附件
        for i in settings.ATTAFILE:
            file = os.path.splitext(i)
            fileName,fileType = file
            if fileType == '.txt':
                fileName = MIMEText(open(settings.ATTAPATH + '\\' + i, 'rb').read(),'base64',settings.MAILCONTENTCODE)
                fileName["Content-Type"] = 'application/octet-stream'
                # filename写什么名字，邮件中显示什么名字
                fileName.add_header("Content-Disposition", "attachment", fileName=(settings.ATTACHCODE, "", i))
                # fileName["Content-Disposition"] = 'attachment; filename=fileName.txt'
                msg.attach(fileName)
            elif fileType == '.xlsx':
                fileName = MIMEApplication(open(settings.ATTAPATH + '\\' + i, 'rb').read())
                fileName["Content-Type"] = 'application/octet-stream'
                fileName.add_header('Content-Disposition', 'attachment', filename=('gbk', '', i))

                # 添加附件到邮件信息
                msg.attach(fileName)
            else:
                print("Unsupported attachment type.")
    elif settings.MAILTYPE == 'HTMLPIC':
        msg = MIMEMultipart('related')
        msgAlternative = MIMEMultipart('alternative')
        msg.attach(msgAlternative)
        msgAlternative.attach(MIMEText(settings.MAILBODY, settings.MAILCONTENTFMT, settings.MAILCONTENTCODE))

        # 指定图片目录
        fp = open(settings.ATTAPATH + '\\' + settings.PICNAME, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()

        # 定义图片 ID，在 HTML 文本中引用
        msgImage.add_header('Content-ID', 'imageid')
        msg.attach(msgImage)
    else:
        print("Please make sure your mail type.")

    # 设置发送者
    userFrom = settings.SENDER.split('@')[0]
    msg['From'] = userFrom + '<' + settings.SENDER + '>'
    # 设置接受者
    userToSet = set()
    for member in settings.RECEIVERS:
        userTo = member.split('@')[0]
        userMail = userTo + '<' + member + '>'
        userToSet.add(userMail)
    print(userToSet)
    msg['To'] = ','.join(userToSet)

    # 设置邮件头信息
    msg['Subject'] = Header(settings.MAILSUBJECT, settings.MAILCONTENTCODE)

    try:
        #  根据配置文件中邮件登录方式，登录邮件服务器，发送邮件
        if settings.MAILAUTH == 'plain':
            smtp = smtplib.SMTP(settings.MAILHOST, settings.MAILHOSTPORT)
        elif settings.MAILAUTH == 'ssl':
            smtp = smtplib.SMTP_SSL(settings.MAILHOST, settings.MAILHOSTPORT)
        else:
            print("Unsupported mail auth method!")
        smtp.login(settings.SENDER, settings.MAILPASS)

        # 发送邮件 参数1：发件人邮箱地址 参数2：收件人地址 参数3：邮件内容格式
        smtp.sendmail(settings.SENDER,settings.RECEIVERS,msg.as_string())
        print('Send mail successfully!')
    except Exception as e:
        print(e)
        print('Send mail failed.')
    finally:
        # 关闭smtp对象
        smtp.quit()

